package com.pig4cloud.pigx.common.customize.api.config;

import com.pig4cloud.pigx.common.customize.api.annotation.OpenApi;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;

/**
 * {@link OpenApi} 映射处理器
 *
 * @since 2022/10/27 10:28
 */
public class OpenApiHandlerMapping extends RequestMappingHandlerMapping {

	/**
	 * 根据控制器类获取请求匹配条件
	 *
	 * @param handlerType 控制器类
	 * @return {@link RequestCondition< OpenApiCondition>}
	 * @since 2022/10/27 11:45
	 */
	@Override
	protected RequestCondition<OpenApiCondition> getCustomTypeCondition(Class<?> handlerType) {
		OpenApi apiVersion = AnnotationUtils.findAnnotation(handlerType, OpenApi.class);
		return createCondition(apiVersion);
	}

	/**
	 * 根据控制器方法获取请求匹配条件
	 *
	 * @param method 控制器方法
	 * @return {@link RequestCondition< OpenApiCondition>}
	 * @since 2022/10/27 11:45
	 */
	@Override
	protected RequestCondition<OpenApiCondition> getCustomMethodCondition(Method method) {
		OpenApi apiVersion = AnnotationUtils.findAnnotation(method, OpenApi.class);
		return createCondition(apiVersion);
	}

	/**
	 * 根据 {@link OpenApi} 的配置创建请求匹配条件
	 *
	 * @param openApi 开放api注解
	 * @return {@link RequestCondition< OpenApiCondition>}
	 * @since 2022/10/27 11:47
	 */
	private RequestCondition<OpenApiCondition> createCondition(OpenApi openApi) {
		// 如果有@OpenApi注解，创建自定义条件
		return openApi == null ? null : new OpenApiCondition(openApi.version());
	}
}
